class Cloak {
  // ul元素
  box = null
  // ul中所有的div元素
  div_list = null
  // ul中所有的span元素
  span_list = null
  // span激活定时器的编号
  spanTimer = 0
  // showTime的定时器编号
  showTimer = 0

  constructor(box) {
    this.box = document.querySelector(box)
    this.div_list = this.box.getElementsByTagName('div')
    this.span_list = this.box.getElementsByTagName('span')
    this.showTime()
    this.activeSpan()
  }

  // 激活span元素的状态
  activeSpan = () => {
    if (this.spanTimer) {
      clearInterval(this.spanTimer)
    }
    this.spanTimer = setInterval(() => {
      if (this.span_list[0].className) {
        this.span_list[0].className = ''
        this.span_list[1].className = ''
      } else {
        this.span_list[0].className = 'active'
        this.span_list[1].className = 'active'
      }
    }, 500)
  }

  // 执行显示功能
  showTime = () => {
    if (this.showTimer) {
      clearInterval(this.showTimer)
    }
    this.showTimer = setInterval(() => {
      this.doShowTime()
    }, 1000)
  }

  // 显示时钟
  doShowTime = () => {
    let timeStr = this.getTimeString()
    // 遍历时间字符串
    for (let i = 0; i < timeStr.length; i++) {
      let div = this.div_list[i]
      let imgs = div.getElementsByTagName('img')
      if (div.t !== timeStr[i]) {
        imgs[1].src = './img/' + timeStr[i] + '.jpg'
        // 调用move函数
        this.move(div, () => {
          imgs[0].src = './img/' + timeStr[i] + '.jpg'
          div.style.top = '0px'
        })
      }
      div.t = timeStr[i]
    }
  }

  // div向上滑动70px的函数，当滑动距离top=-70时，top重置为0，修改div中第一张图片的src地址
  move = (div, fn) => {
    let top = 0
    let id = setInterval(() => {
      top -= 3
      if (top <= -70) {
        top = -70
        clearInterval(id)
      }
      div.style.top = top + 'px'
      // top=-70并且fn是函数，调用函数fn
      top === -70 && this.isFunction(fn) ? fn() : ''
    }, 30)
  }

  // 判断n是否是函数
  isFunction = (n) => {
    return Object.prototype.toString.call(n).slice(8, -1) === 'Function'
  }

  // 获得时钟的字符串
  getTimeString = () => {
    // 创建时间
    let date = new Date()
    let h = (date.getHours() + '').padStart(2, '0')
    let m = (date.getMinutes() + '').padStart(2, '0')
    let s = (date.getSeconds() + '').padStart(2, '0')
    return [h, m, s].join('')
  }
}
